package com.oocl.im.ui;

import com.oocl.im.action.impl.LoginAction;
import com.oocl.im.entity.Protocol;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.oocl.im.main.ClientRunnable;
import com.oocl.im.constants.ClientMaintenance;
import com.oocl.im.constants.Constants;

public class LoginFrame extends JFrame implements ActionListener {
	private JTextField nameTf;
	private JPasswordField psdPf;
	private JButton loginBtn;
	private JButton cancelBtn;

	public LoginFrame() {
		this.setSize(400, 260);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		init();
		addEvent();
		this.setVisible(true);
	}

	private void init() {

		this.setLayout(null);
		nameTf = new JTextField();
		psdPf = new JPasswordField();
		loginBtn = new JButton("login");
		cancelBtn = new JButton("cancel");
		nameTf.setBounds(20, 20, 300, 40);
		psdPf.setBounds(20, 80, 300, 40);
		loginBtn.setBounds(60, 140, 90, 40);
		cancelBtn.setBounds(200, 140, 90, 40);
		this.add(nameTf);
		this.add(psdPf);
		this.add(loginBtn);
		this.add(cancelBtn);

	}

	private void addEvent() {
		loginBtn.addActionListener(this);
		cancelBtn.addActionListener(this);
	}

	public void actionPerformed(ActionEvent e) {
		Protocol protocol = null;

		switch (e.getActionCommand()) {
		case "login":
			try {
				ClientMaintenance.socket = new Socket(Constants.SERVER_HOST,
						Constants.SERVER_PORT);
				OutputStream os = ClientMaintenance.socket.getOutputStream();

				ClientMaintenance.oos = new ObjectOutputStream(os);

				InputStream is = ClientMaintenance.socket.getInputStream();
				ClientMaintenance.ois = new ObjectInputStream(is);

				LoginAction action = new LoginAction(ClientMaintenance.oos);
				this.setVisible(false);
				action.setAccount(nameTf.getText());
				action.execute(protocol);
				new Thread(new ClientRunnable()).start();
			} catch (IOException e1) {
				
				e1.printStackTrace();
			}
			break;
		case "cancel":
			System.exit(0);
		}
	}
}
